<template>
  <div class="dialog">
    <el-form :inline="true" :model="params" class="demo-form-inline">
      <el-form-item label="选择门店">
        <el-select v-model="params.shopId">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="params.flag">
          <el-option label="全部" value=""></el-option>
          <el-option label="已参与拍卖" value="3"></el-option>
          <el-option label="已打包" value="2"></el-option>
          <el-option label="已评估" value="1"></el-option>
          <el-option label="未评估" value="0"></el-option></el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" style="margin-left: 100px">查询</el-button>
        <el-button type="primary" @click="onAddShop" style="margin-left: 10px">添加库存</el-button>
        <el-button type="primary" @click="onPackageSource" style="margin-left: 10px">打包车源</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading" size="small"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :selectable="selectable">
      </el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>车辆描述：{{ props.row.carDesc }}</span>
            </div>
            <el-image v-for="url in props.row.carImages" :key="url" :src="url" lazy></el-image>
          </el-card>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="序号" align="center" > </el-table-column>
      <el-table-column prop="shopName" label="门店名称" align="center" :show-overflow-tooltip='true'></el-table-column>
      <el-table-column prop="brandName" label="品牌/车系/车型" align="center" :show-overflow-tooltip='true'>
        <template slot-scope="scope">
          {{ scope.row.brandName}}   {{ scope.row.seriesName}}   {{ scope.row.specName}}  {{scope.row.carName}}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="seriesName" label="车系" align="center"></el-table-column>
      <el-table-column prop="specName" label="车型" align="center"></el-table-column> -->
      <el-table-column prop="vin" label="车架号" align="center" :show-overflow-tooltip='true'></el-table-column>
      <!-- <el-table-column prop="contactTel" label="车辆图片" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="onShowCarImages(scope.row)">查看图片</el-button>
            </template>
      </el-table-column>
      <el-table-column prop="carDesc" label="车辆描述" align="center"></el-table-column> -->
      <el-table-column prop="flag" label="状态" align="center" width="140" :show-overflow-tooltip='true'>
        <template slot-scope="scope">
          <span v-if="scope.row.flag == 3" style="color: #67C23A;">已参与拍卖</span>
          <template v-if="scope.row.flag == 2">
            <span style="color: #67C23A;">已打包</span><br>
            <el-button type="primary" size="mini" @click="onLookPingGu(scope.row)">评估详情</el-button>
          </template>
          <template v-if="scope.row.flag == 1">
            <span style="color: #67C23A;">已评估</span><br />
            <el-button type="primary" size="mini" @click="onLookPingGu(scope.row)">评估详情</el-button>
          </template>
          <template v-else>
            <span v-if="scope.row.flag == 0" style="color: #F56C6C;">未评估</span>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" :show-overflow-tooltip='true'></el-table-column>
      <!-- <el-table-column prop="updateTime" label="更新时间" align="center" width="150"></el-table-column> -->
      <el-table-column label="操作" align="center" fixed="right" width="140">
        <template slot-scope="scope">
          <template v-if="scope.row.flag == 0">
            <el-button type="text" size="mini" @click="onEditShop(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" style="color: #F56C6C;" @click="onDelete(scope.row)">删除</el-button>
          </template>

        </template>
      </el-table-column>
    </el-table>
    <div class="block" style="float: left; margin-top: 20px">
      <div>
        <span style="
            padding-top: 10px;
            display: inline-block;
            vertical-align: middle;
            color: #606266;
            font-size: 14px;
          ">显示第{{ this.params.page }}页的{{ this.params.rows }}条记录，总共{{
            this.total
          }}条记录
        </span>
      </div>
    </div>
    <div class="block" style="float: right; margin-top: 20px">
      <el-pagination :current-page.sync="params.page" :page-sizes="[10, 20, 50, 100]" :page-size="params.rows" background
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- <el-backtop target=".dialog"></el-backtop> -->

    <el-dialog :visible.sync="editShopVisible" title="编辑库存" width="80%" center>
      <el-form :model="storeData" ref="from" label-width="150px" :rules="rules">
        <el-form-item label="品牌:" prop="brandId">
          <el-select v-model="storeData.brandId" filterable @change="onChangeBrand" clearable >
              <el-option v-for="item in brands" :key="item.id" :label="item.title" :value="item.id">
              </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="车系:">
          <el-select v-model="storeData.seriesId" filterable @change="onChangeSeries" clearable ><el-option
                v-for="item in series" :key="item.id" :label="item.title" :value="item.id">
              </el-option></el-select>
        </el-form-item>
        <el-form-item label="车型:">
          <el-select v-model="storeData.specId" clearable><el-option v-for="item in specs" :key="item.id"  
                :label="item.title" :value="item.id">
              </el-option></el-select>
        </el-form-item>
        <el-form-item label="所属门店">
          <el-select v-model="storeData.shopId" filterable >
            <el-option
                label="无" :value="0">
              </el-option>
            <el-option
                v-for="item in shopList" :key="item.id" :label="item.shopName" :value="item.id">
              </el-option></el-select>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="storeData.carName"></el-input>
        </el-form-item>
        <el-form-item label="VIN:" prop="vin">
          <el-input v-model="storeData.vin"></el-input>
        </el-form-item>
        <el-form-item label="车辆图片:">
          <el-upload action="String" list-type="picture-card" :http-request="uploadImages" :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview" :on-remove="handleImagesRemove" :file-list="carImages">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogImageVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="车辆描述:" prop="carDesc">
          <el-input type="textarea" v-model="storeData.carDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editShopVisible = false">关 闭</el-button>
        <el-button type="primary" @click="handleEditShop">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="carImageVisible" title="评价详情" width="80%" center>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ evaDesc }}</span>
        </div>
        <div class="demo-image__lazy">
          <el-image v-for="url in evaImages" :key="url" :src="url" lazy></el-image>
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="carImageVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="packageVisible" title="打包车源" width="80%" center>
      <el-alert :title="'已选择' + multipleSelection.length + '辆车'" type="success" effect="dark">
      </el-alert>
      <br />
      <el-form :model="packageData" ref="packageFrom" label-width="150px" :rules="packageDataRules">
        <el-form-item label="包名:" prop="packageName1">
          <el-input v-model="packageData.packageName1"></el-input>
          <el-input v-model="packageData.packageName2"></el-input>
          <el-input v-model="packageData.packageName3"></el-input>
          <el-input v-model="packageData.packageName4"></el-input>
        </el-form-item>
        <!-- <el-form-item label="可参与车商:" prop="dealerIds">
          <el-select v-model="packageData.dealerIds" filterable multiple style="width:100%">
            <el-option v-for="item in businessList" :key="item.id" :label="item.dealerName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="佣金(元):">
          <el-input v-model="packageData.commission"></el-input>
        </el-form-item>
        <el-form-item label="代办费(元):">
          <el-input v-model="packageData.checkFee"></el-input>
        </el-form-item>
        <el-form-item label="服务费(元):">
          <el-input v-model="packageData.parkingFee"></el-input>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input type="textarea" v-model="packageData.remark"></el-input>
        </el-form-item>
        <el-form-item label="看车地点:">
          <el-input type="textarea" v-model="packageData.carAddress"></el-input>
        </el-form-item>
        <el-form-item label="联系方式:">
          <el-input type="textarea" v-model="packageData.contact"></el-input>
        </el-form-item>
        <el-form-item label="特别事项:">
          <el-input type="textarea" v-model="packageData.specialItems"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="packageVisible = false">关 闭</el-button>
        <el-button type="primary" @click="handleEditPackage">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="deleteVisible" title="提示" width="450px" center>
      <div class="del-dialog-cnt">确定删除车源吗？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
import {
  getShopList, getStoreList, editStore, delStock, getCarBrand, getCarSeries, getCarSpec, addPackage, upLoadPicture
} from "@/api/carSource";
import {
  getBusinessList
} from "@/api/carBusiness";
import _ from 'lodash';
import * as imageConversion from 'image-conversion';

export default {
  data() {
    return {
      loading: false,
      currentPage4: 4,
      total: 0,
      params: {
        shopId: '',
        flag: '',
      },
      tableData: [],
      shopList: [],
      editShopVisible: false,
      modifyVisible: false,
      deleteVisible: false,
      brands: [],
      series: [],
      specs: [],
      storeData: {
        id: 0,
        brandId: '',
        seriesId: '',
        specId: '',
        carName:'',
        vin: '',
        status: 1,
        carImages: [],
        carDesc: '',
        flag: 0,
        shopId: '0'
      },
      carImages: [],
      rules: {
        brandId: [
          { required: true, message: '请选择品牌', trigger: 'blur' },
        ],
        seriesId: [
          { required: true, message: '请选择车系', trigger: 'blur' },
        ],
        specId: [
          { required: true, message: '请选择车型', trigger: 'blur' },
        ],        
        vin: [
          { required: true, message: '请输入VIN', trigger: 'blur' }
        ],
        carDesc: [
          { required: true, message: '请对车源进行描述', trigger: 'blur' }
        ]
      },
      businessList: [],
      packageData: {
        id: 0,
        packageName: '',
        packageName1:'',
        packageName2:'',
        packageName3:'',
        packageName4:'',
        remark: '',
        stockIds: '',
        dealerIds: '',
        flag: 0,
        parkingFee:'0',//服务费
        checkFee:'0',//代办费
        commission:'0',//佣金
        specialItems:'',
        carAddress:'',
        contact:''
      },
      packageDataRules: {
        packageName1: [
          { required: true, message: '请输入车源包名称', trigger: 'blur' },
        ],
        // dealerIds: [
        //   { required: true, message: '请选择可参与的车商', trigger: 'blur' }
        // ]
      },
      dialogImageUrl: '',
      dialogImageVisible: false,
      carImageVisible: false,
      evaImages: [],
      evaDesc: '',
      multipleSelection: [],
      packageVisible: false
    };
  },

  methods: {
    onSearch() {
      this.getData();
    },
    handleSizeChange(val) {
      this.params.rows = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.params.page = val;
      this.getData();
    },
    getShopList() {
      let params = {
        pageSize: 1000,
        pageNo: 1,
      }
      getShopList(params).then((res) => {
        this.shopList = res.data.rows
      });
    },
    getData(exportExcel) {
      if (exportExcel) {
        this.params.export = true
      } else {
        this.loading = true;
        let params = {
          pageSize: this.params.rows,
          pageNo: this.params.page,
          filter: [],
          orderType:'desc',
          orderField:'id'
        }
        if (this.params.shopId != '') {
          params.filter.push({
            field: 'shopId',
            operator: 'EQ',
            value: this.params.shopId
          })
        }
        if (this.params.flag != '') {
          params.filter.push({
            field: 'flag',
            operator: 'EQ',
            value: this.params.flag
          })
        }
        getStoreList(params).then((res) => {
          _.forEach(res.data.rows, function (value, key) {
            if (value.carImages != null && value.carImages != "") {
              var imgs = value.carImages.split(",");
              for (var index = 0; index < imgs.length; index++) {
                console.log(process.env.VUE_APP_BASE_URL+imgs[index])
                imgs[index] = process.env.VUE_APP_BASE_URL + imgs[index]
              }
              value.carImages = imgs;
            }
          });

          this.loading = false;
          this.total = res.data.total;
          this.tableData = res.data.rows;
        });
      }
    },
    onEditShop(row) {
      this.resetStoreForm();
      this.editShopVisible = true;
      getCarBrand().then((res) => {
        this.brands = res.data;
        var data = _.clone(row);
        var that = this;
        _.forEach(data.carImages, function (value, key) {
          that.carImages.push({
            uid: value,
            url: value
          })
        });
        // console.log(this.carImages)
        this.storeData = data;
        this.onChangeBrand(row.brandId);
        this.onChangeSeries(row.seriesId);
      });
    },
    onDelete(row) {
      this.deleteVisible = true;
      this.storeData.id = row.id;
    },
    handleEditShop() {
      this.$refs['from'].validate((valid) => {
        if (valid) {
          var images = [];
          _.forEach(this.carImages, function (value, key) {
            var url = value.url.replace(process.env.VUE_APP_BASE_URL, '');
            images.push(url)
          });
          this.storeData.carImages = images
          editStore(this.storeData).then((res) => {
            this.getData();
            this.editShopVisible = false;
            this.resetPackageForm();
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleDelete() {
      delStock(this.storeData.id).then((res) => {
        this.getData();
        this.deleteVisible = false;
      });
    },
    onAddShop() {
      this.resetStoreForm();
      getCarBrand().then((res) => {
        this.brands = res.data;
      });
      this.editShopVisible = true;
    },
    onChangeBrand(val) {
      getCarSeries(val).then((res) => {
        this.series = res.data;
      });
    },
    onChangeSeries(val) {
      getCarSpec(val).then((res) => {
        this.specs = res.data;
      });
    },
    onLookPingGu(row) {
      this.evaDesc = row.evaDesc;
      if (row.evaImages != null && row.evaImages != "") {
        var imgs = row.evaImages.split(",");
        for (var index = 0; index < imgs.length; index++) {
          imgs[index] = process.env.VUE_APP_BASE_URL + imgs[index]
        }
        this.evaImages = imgs;
      }
      this.carImageVisible = true;
    },
    handleImagesRemove(file, fileList) {
      console.log(file, fileList);
      this.carImages = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
    uploadImages(item) {
      const formData = new FormData()
      formData.append('file', item.file)
      upLoadPicture(formData).then(res => {
        if (res) {
          this.$message.success('上传成功！')
          this.carImages.push({ uid: res.data, url: process.env.VUE_APP_BASE_URL + res.data })
          // this.storeData.carImages.push(res.data)
          // console.log(res)
        }
      }).catch(err => {
        this.$message.error('上传失败，请重新上传')
        console.log('报错', err)
      })
    },
    beforeUpload(file) {
      const _that = this
      // const isJpgOrPng =
      //   file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 1;
      // if (!isJpgOrPng) {
      //   this.$message.error("上传图片只能是 JPG 或 PNG 格式!");
      //   return false;
      // }
      return new Promise((resolve) => {
        // 小于2M 不压缩
         if (isLt2M) {
          resolve(file)
        }
        // 压缩到400KB,这里的400就是要压缩的大小,可自定义
        imageConversion.compressAccurately(file, 400).then((res) => {
          console.log(res);
          resolve(res);
        });
        //compressAccurately有多个参数时传入对象
        //imageConversion.compressAccurately(file, {
        // size: 1024, //图片大小压缩到1024kb
        // width:1280 //宽度压缩到1280
        //}).then(res => {
        //resolve(res)
        //})
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    selectable: function (row, index) {
      if (row.flag == 1) {
        return true;
      }
    },
    onPackageSource() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: '请选择要打包的车源',
          type: 'warning'
        });
        return;
      }
      this.resetPackageForm();
      getBusinessList({ pageNo: 1, pageSize: 1000 }).then((res) => {
        this.businessList = res.data.rows;
        // console.log(this.businessList);
        var dealerIds = [];
        _.forEach(this.businessList, function (value, key) {
          dealerIds.push(value.id)
        });
        this.packageData.dealerIds = dealerIds;
      });
      this.packageVisible = true;
      var stockIds = [];
      _.forEach(this.multipleSelection, function (value, key) {
        stockIds.push(value.id)
      });
      this.packageData.stockIds = stockIds;
    },
    handleEditPackage() {
      this.$refs['packageFrom'].validate((valid) => {
        if (valid) {
          this.packageData.packageName = this.packageData.packageName1+"#"+
          this.packageData.packageName2+"#"+
          this.packageData.packageName3+"#"+
          this.packageData.packageName4
          addPackage(this.packageData).then((res) => {
            this.getData();
            this.packageVisible = false;
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetStoreForm() {
      this.storeData = {
        id: 0,
        brandId: '',
        seriesId: '',
        specId: '',
        carName:'',
        vin: '',
        status: 1,
        carImages: [
        ],
        carDesc: '',
        flag: 0,
        shopId: 0,
      }
      this.carImages = [];
    },
    resetPackageForm() {
      this.packageData = {
        id: 0,
        packageName: '',
        packageName1:'',
        packageName2:'',
        packageName3:'',
        packageName4:'',
        remark: '',
        stockIds: '',
        dealerIds: '',
        flag: 0,
        parkingFee:'0',//停车费
        checkFee:'0',//检测费
        commission:'0',//佣金
        specialItems:'',
        carAddress:'',
        contact:''
      }
    }
  },
  mounted() {
    this.getData();
    this.getShopList();
  },
};
</script>
<style scoped lang="scss">
.my-radio {
  margin-bottom: 10px;
}

.dialog {
  width: 95%;
  height: 100%;
  padding-top: 10px;
  margin-left: 10px;
}
</style>
